package vip.meeet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import vip.meeet.utils.HttpUtil;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Map;

/**
 * 索引别名
 * https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html
 * @TODO 一对多，多对一，routing，filter
 */
public class AliasHelper {

    private static final String ALIAS_BASE = "{ \"%s\" : { \"index\" : \"%s\", \"alias\" : \"%s\" } }";

    private static final String ADD = "add";

    private static final String REMOVE = "remove";

    private static final String ACTIONS = "actions";

    private static final String ALIAS_URL = "http://%s/_aliases";

    public static String addAlias(String hostPort,String index,String alias) throws IOException {
        return doAction(hostPort,ADD,index,alias);
    }

    public static String removeAlias(String hostPort,String index,String alias) throws IOException {
        return doAction(hostPort,REMOVE,index,alias);
    }

    public static String getAliasFromIndex(String hostPort,String index) throws IOException {
        String urlBase = "http://%s/%s/_alias/*";
        String url = String.format(urlBase, hostPort, index);
        return HttpUtil.getContent(url);
    }

    public static String getAliasFromAlias(String hostPort,String alias) throws IOException {
        String urlBase = "http://%s/*/_alias/%s";
        String url = String.format(urlBase, hostPort, alias);
        return HttpUtil.getContent(url);
    }

    private static String doAction(String hostPort,String action,String index,String alias) throws IOException {
        JSONObject body = new JSONObject();
        JSONArray actions = new JSONArray();
        String actionString = String.format(ALIAS_BASE, action, index, alias);
        JSONObject actionJson = JSON.parseObject(actionString);
        actions.add(actionJson);
        body.put(ACTIONS,actions);
        String url = String.format(ALIAS_URL, hostPort);
        return HttpUtil.postJsonContent(url,body.toJSONString());
    }

    public static String aliasBody(Map<String,String> addAlias, Map<String,String> removeAlias){
        JSONObject body = new JSONObject();
        JSONArray actions = new JSONArray();
        LinkedList<JSONObject> as = new LinkedList<>();
        for(Map.Entry<String, String> entry : addAlias.entrySet()){
            String addContent = String.format(ALIAS_BASE, ADD, entry.getKey(), entry.getValue());
            as.add(JSON.parseObject(addContent));
        }

        for(Map.Entry<String, String> entry : removeAlias.entrySet()){
            String removeContent = String.format(ALIAS_BASE, REMOVE, entry.getKey(), entry.getValue());
            as.add(JSON.parseObject(removeContent));
        }
        actions.addAll(as);
        body.put(ACTIONS,actions);
        return body.toJSONString();
    }
}
